package quq.missq.activity;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.google.gson.Gson;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import quq.missq.BaseActivity;
import quq.missq.Constants;
import quq.missq.MissQApplication;
import quq.missq.R;
import quq.missq.beans.BaseBean;
import quq.missq.beans.School;
import quq.missq.beans.UserBean;
import quq.missq.utils.BitmapUtils;
import quq.missq.utils.HttpRequest;
import quq.missq.utils.ImageUploadAsyncTask;
import quq.missq.utils.ImageUtil;
import quq.missq.utils.MD5;
import quq.missq.utils.UserTools;
import quq.missq.utils.VolleyTool;

public class RegisterDataActivity extends BaseActivity implements View.OnClickListener, VolleyTool.HTTPListener {

    private static final int SELECT_PIC = 0;
    private static final int SCHOOL_CHOOSE = 1;

    private ImageView mIcon;
    private ImageView mBack;
    private TextView mSchool;
    private TextView mAge;
    private EditText mNickName;
    private String verify_token, phoneNumber, password = "";
    private DatePickerDialog mDatePickerDialog;
    private RelativeLayout mRegister;
    private RelativeLayout mBoy;
    private RelativeLayout mGirl;
    private ProgressDialog dialog;
    private int mGender = 1;
    private String mPath = "";
    private int mSchoolId = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register_data_activity);
        Bundle bundle = getIntent().getExtras();
        verify_token = bundle.getString("verify_token");
        phoneNumber = bundle.getString("phoneNumber");
        password = bundle.getString("password");
        initView();
        initListener();
    }

    private void initView() {
        mIcon = (ImageView) findViewById(R.id.icon);
        mBack = (ImageView) findViewById(R.id.back);
        mSchool = (TextView) findViewById(R.id.school);
        mAge = (TextView) findViewById(R.id.age);
        mRegister = (RelativeLayout) findViewById(R.id.register);
        mNickName = (EditText) findViewById(R.id.nickName);
        mBoy = (RelativeLayout) findViewById(R.id.boy);
        mGirl = (RelativeLayout) findViewById(R.id.girl);
    }

    private void initListener() {
        mIcon.setOnClickListener(this);
        mBack.setOnClickListener(this);
        mSchool.setOnClickListener(this);
        mAge.setOnClickListener(this);
        mRegister.setOnClickListener(this);
        mBoy.setOnClickListener(this);
        mGirl.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.icon:
                intent = new Intent(this, SelectPicActivity.class);
                intent.putExtra(SelectPicActivity.KEY_CUT_X,1);
                intent.putExtra(SelectPicActivity.KEY_CUT_Y,1);
                startActivityForResult(intent, SELECT_PIC);
                break;
            case R.id.back:
                finish();
                break;
            case R.id.school:
                intent = new Intent(this, SchoolChooseActivity.class);
                startActivityForResult(intent, SCHOOL_CHOOSE);
                break;
            case R.id.age:
                mDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        mAge.setText(year + "-" + (monthOfYear+1)+ "-" + dayOfMonth);
                    }
                }, 1990, 1, 1);
                mDatePickerDialog.show();
                break;
            case R.id.register:
                register();
                break;
            case R.id.boy:
                mGender = 1;
                mBoy.setBackgroundResource(R.mipmap.gender_bg);
                mGirl.setBackgroundResource(0);
                break;
            case R.id.girl:
                mGender = 2;
                mGirl.setBackgroundResource(R.mipmap.gender_bg);
                mBoy.setBackgroundResource(0);
                break;
        }

    }

    private void register() {
        if ("".equals(mPath)) {
            showToast("请上传头像");
            return;
        }
        String nickName = mNickName.getText().toString();
        String school = mSchool.getText().toString();
        String age = mAge.getText().toString();
        if ("".equals(nickName)) {
            showToast("请填写昵称");
            return;
        }
        if ("".equals(school)) {
            showToast("请填写学校");
            return;
        }
        if ("".equals(age)) {
            showToast("请填写年龄");
            return;
        }
        dialog = ProgressDialog.show(this, "提示", "验证中。。。", false, false);
        Map<String, String> params = new HashMap<>();
        params.put("mobile", phoneNumber);
        params.put("password", MD5.getMD5(MD5.getMD5(password)));
        params.put("nkname", nickName);
        params.put("gender", mGender + "");
        params.put("birthday", age);
        params.put("schoolId", mSchoolId + "");
        params.put("verifyToken", verify_token);
        params.put("schoolName", school);
        Map<String, File> files = new HashMap<>();
        Log.i("params=========",params.toString());
        files.put("pic", new File(mPath));
        ImageUploadAsyncTask imageUploadAsyncTask = new ImageUploadAsyncTask(params, files, Constants.REGISTER_URL, new HttpRequest.HttpRequestListener() {
            @Override
            public void httpError() {
                if (dialog != null) {
                    dialog.dismiss();
                }
                showToast("上传失败，请重试");
            }

            @Override
            public void httpSuccess(String msg) {
                Log.i("msg====",msg);
                if (dialog != null) {
                    dialog.dismiss();
                }

                Gson gson = new Gson();
                BaseBean b = gson.fromJson(msg,BaseBean.class);
                if(b.getCode()<0){
                    showToast(b.getMessage());
                    return;
                }
               final UserBean user = gson.fromJson(msg, UserBean.class);

                UserTools.saveUser(RegisterDataActivity.this, user.getData());
                // 加个登陆试试
                EMChatManager.getInstance().login(user.getData().getId()+"",MD5.getMD5(MD5.getMD5(password)),new EMCallBack() {
                    @Override
                    public void onSuccess() {
                        //  Toast.makeText(TaPageActivity.this, "chenggong" + MD5.getMD5(MD5.getMD5(user.getPassword())), Toast.LENGTH_SHORT).show();
                        // 登陆成功，保存用户名密码
                        MissQApplication.getInstance().setUserName(user.getData().getId()+"");
                        MissQApplication.getInstance().setPassword(MD5.getMD5(MD5.getMD5(password)));

                        // 更新当前用户的nickname 此方法的作用是在ios离线推送时能够显示用户nick
                        boolean updatenick = EMChatManager.getInstance().updateCurrentUserNick(
                                user.getData().getNkname());
                        Log.e("xxxxx","sssss");
                    }

                    @Override
                    public void onError(int i, String s) {

                    }

                    @Override
                    public void onProgress(int i, String s) {

                    }
                });
                // ////////////////



                //finish();
                //showToast("登录成功");

                setResult(RESULT_OK);
                finish();
            }
        }, "file");
        imageUploadAsyncTask.execute();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == SELECT_PIC) {
            mPath = data.getStringExtra(SelectPicActivity.KEY_PHOTO_PATH);
            mIcon.setImageBitmap(BitmapUtils.toRoundBitmap(ImageUtil.readFile(mPath), 3, R.color.white));
        } else if (resultCode == RESULT_OK && requestCode == SCHOOL_CHOOSE) {
            Bundle bundle = data.getExtras();
            School school = (School) bundle.getSerializable("school");
            mSchool.setText(school.getM_nUniversity_Name());
            mSchoolId = school.getM_nUniversity_ID();
        }
    }

    @Override
    public <T> void onResponse(T t, int requestCode) {
        switch (requestCode) {
            case Constants.GET_CODE:
                showToast("验证码发送成功，请注意查收");
                break;
            case Constants.VERIFY_CODE:
                break;
        }
    }


    @Override
    public void onErrorResponse(VolleyError error, int requestCode) {
//        if (dialog != null && dialog.isShowing()) {
//            dialog.dismiss();
//        }

    }


}
